﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.Practices.EnterpriseLibrary.Data;
using System.Data;
using System.Text;

public partial class MRP_ViewProductPrice : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Database db = DatabaseFactory.CreateDatabase("MRPSqlServer");
            string sSQL = ("SELECT ID, CustomerCode+'('+CompanyName+')' as CustomerName  FROM MRP_Customer;");
            sSQL += "SELECT MRP_MaterialMain.ID,MRP_MaterialMain.MCode, MRP_MaterialMain.Name, MRP_MaterialMain.DiagramCode, MRP_MaterialMain.Weight,View_ProductSize_List.DisplayText FROM MRP_MaterialMain Left JOIN View_ProductSize_List ON MRP_MaterialMain.SizeType = View_ProductSize_List.ID WHERE (MRP_MaterialMain.MType = 5)";
            DataSet ds = db.ExecuteDataSet(CommandType.Text, sSQL);

            DropDownList1.DataSource = ds.Tables[0].DefaultView;
            DropDownList1.DataTextField = "CustomerName";
            DropDownList1.DataValueField = "ID";
            DropDownList1.DataBind();
            //Database db = DatabaseFactory.CreateDatabase("MRPSqlServer");
            //string sSQL = "SELECT MRP_MaterialMain.ID,MRP_MaterialMain.MCode, MRP_MaterialMain.Name, MRP_MaterialMain.DiagramCode, MRP_MaterialMain.Weight,View_ProductSize_List.DisplayText FROM MRP_MaterialMain Left JOIN View_ProductSize_List ON MRP_MaterialMain.SizeType = View_ProductSize_List.ID WHERE (MRP_MaterialMain.MType = 5)";
            //DataSet ds = db.ExecuteDataSet(CommandType.Text, sSQL);

            DropDownList2.DataSource = ds.Tables[1].DefaultView;
            DropDownList2.DataTextField = "MCode,Name";
            DropDownList2.DataValueField = "ID";
            DropDownList2.DataTextFormatString = "{0}({1})";
            DropDownList2.DataBind();

            string outHTML = GetPriceInfo(0,0);
            this.priceInfo.InnerHtml = outHTML.ToString();
        }



    }
    private string DisplayIfNotNULL(object inText)
    {
        string sRet=inText as string;

        return (string.IsNullOrEmpty(sRet) ? "<未设置>" : sRet);
    }
    private string GetPriceFormat(string price, string currency, string tax)
    {
        Decimal d = Decimal.Parse(price);

        int i=price.IndexOf('.');
        if (i > 0)
        {
            
                while ((price.Substring(price.Length - 1, 1) == "0")&&(i < price.Length - 3))
                    price = price.Remove(price.Length - 1);
        }

        string sRet = string.Empty;
        if (currency.Equals("2"))
        {
            return string.Format("${0}", price);
        }
        else
        {
            return string.Format("￥{0}", price); 
        }
    }
    protected void RadioButton2_CheckedChanged(object sender, EventArgs e)
    {
        
    }
    protected void RadioButton3_CheckedChanged(object sender, EventArgs e)
    {
        
    }
    protected void DropDownList2_DataBinding(object sender, EventArgs e)
    {

    }
    protected void RadioButton1_CheckedChanged(object sender, EventArgs e)
    {
        if (this.RadioButton1.Checked)
        {
            string outHTML = GetPriceInfo(0,0);
            this.priceInfo.InnerHtml = outHTML.ToString();
        }
    }
    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        this.RadioButton2.Checked = true;
        int iCustomerID = Int32.Parse(DropDownList1.SelectedValue);
        string outHTML = GetPriceInfo(iCustomerID, 0);
        this.priceInfo.InnerHtml = outHTML.ToString();

    }
    protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
    {
        this.RadioButton3.Checked = true;
        int iProductID = Int32.Parse(DropDownList2.SelectedValue);
        string outHTML = GetPriceInfo(0, iProductID);
        this.priceInfo.InnerHtml = outHTML.ToString();
    }

    private string GetPriceInfo(int CustomerID,int ProductID)
    {
        StringBuilder outHTML = new StringBuilder();
        StringBuilder whereSQL =new StringBuilder();
        whereSQL.Append(" 1=1 ");

        if (CustomerID > 0)
        {
            whereSQL.AppendFormat("AND CustomerID={0} ", CustomerID);
        }
        if (ProductID > 0)
        {
            whereSQL.AppendFormat("AND ProductID={0} ", ProductID);
        }
        Database db = DatabaseFactory.CreateDatabase("MRPSqlServer");
        //string sSQL = "SELECT MRP_Customer.CompanyName,MRP_Customer.CustomerCode, MRP_MaterialMain.Name as ProductName, MRP_MaterialMain.MCode,MRP_CustomerProductPrice.Price,MRP_CustomerProductPrice.PriceStartDate, MRP_CustomerProductPrice.PriceEndDate FROM MRP_CustomerProductDefinition INNER JOIN MRP_Customer ON MRP_CustomerProductDefinition.CustomerID = MRP_Customer.ID INNER JOIN MRP_MaterialMain ON MRP_CustomerProductDefinition.ProductID = MRP_MaterialMain.ID LEFT OUTER JOIN MRP_CustomerProductPrice ON MRP_CustomerProductDefinition.CustomerID = MRP_CustomerProductPrice.CustomerID AND MRP_CustomerProductDefinition.ProductID = MRP_CustomerProductPrice.ProductID order by 2";
        StringBuilder sb = new StringBuilder();
        if (CustomerID > 0)
        {
            sb.AppendFormat("SELECT ID as CustomerID, CompanyName, CustomerCode FROM MRP_Customer where ID={0};", CustomerID);
        }
        else
            sb.Append("SELECT ID as CustomerID, CompanyName, CustomerCode FROM MRP_Customer;");

        sb.Append("SELECT MRP_MaterialMain.Name as ProductName, MRP_MaterialMain.MCode, MRP_CustomerProductDefinition.CustomerID, MRP_CustomerProductDefinition.ProductID,View_ProductSize_List.DisplayText as productSize, MRP_MaterialMain.Weight, MRP_MaterialMain.DiagramCode ");
        //if (CustomerID > 0)
        {
            sb.AppendFormat("FROM MRP_CustomerProductDefinition INNER JOIN MRP_MaterialMain ON MRP_CustomerProductDefinition.ProductID = MRP_MaterialMain.ID left JOIN View_ProductSize_List ON MRP_MaterialMain.SizeType = View_ProductSize_List.ID where {0} order by MCode;", whereSQL.ToString());
        }

        sb.AppendFormat("Select ID, CustomerID, ProductID, Price, PriceStartDate, PriceEndDate, CurrencyType, Tax FROM MRP_CustomerProductPrice where PriceEndDate>=GetDate() and {0} order by CustomerID, ProductID, PriceStartDate;", whereSQL.ToString());

        DataSet ds = db.ExecuteDataSet(CommandType.Text, sb.ToString());
        ds.Relations.Add("ProductsForCustomer", ds.Tables[0].Columns["CustomerID"], ds.Tables[1].Columns["CustomerID"]);

        ds.Relations.Add("PriceOfProduct", new DataColumn[] { ds.Tables[1].Columns["CustomerID"], ds.Tables[1].Columns["ProductID"] }, new DataColumn[] { ds.Tables[2].Columns["CustomerID"], ds.Tables[2].Columns["ProductID"] });
        //int iCount1;

        foreach (DataRow customer in ds.Tables[0].Rows)
        {
            
            if (customer.GetChildRows("ProductsForCustomer").Count() == 0)
                continue;
            
            outHTML.AppendFormat("<div class=\"CustomerInPriceInfo\">{0}(客户编号：{1})：", customer["CompanyName"], customer["CustomerCode"]);
            foreach (DataRow product in customer.GetChildRows("ProductsForCustomer"))
            {
                outHTML.AppendFormat("<div class=\"productInfoInPriceInfo\"><div class=\"productTitleInPriceInfo\"><div class=\"productNameInPriceInfo\">{1}</div>(产品：{0},型号：{2},单重：{3},图纸编号：{4})：</div>", product["ProductName"], product["MCode"],
                    DisplayIfNotNULL(product["productSize"]), DisplayIfNotNULL(product["Weight"]), DisplayIfNotNULL(product["DiagramCode"]));
                int i = 0;
                DataRow curPrice = null;
                foreach (DataRow price in product.GetChildRows("PriceOfProduct"))
                {
                    if (i == 0)
                    {
                        outHTML.Append("<table class=\"tableInPriceInfo\"><tr>");
                        outHTML.AppendFormat("<td class=\"dateInPriceInfo\">|<br/>{0:d}</td><td><div class=\"priceInPriceInfoCurrent\">{1}</div></td>", price["PriceStartDate"], GetPriceFormat(price["Price"].ToString(), price["CurrencyType"].ToString(), price["Tax"].ToString()), price["PriceEndDate"]);
                    }
                    else
                        outHTML.AppendFormat("<td class=\"dateInPriceInfo\">|<br/>{0:d}</td><td><div class=\"priceInPriceInfo\">{1}</div></td>", price["PriceStartDate"], GetPriceFormat(price["Price"].ToString(), price["CurrencyType"].ToString(), price["Tax"].ToString()), price["PriceEndDate"]);
                    curPrice = price;



                    i++;
                }
                if (i == 0)
                {
                    outHTML.Append("<table><tr><td class=\"unPriceInPriceInfo\">目前没有定价。</td>");
                    outHTML.AppendFormat("<td><a href=\"MRP_Customer_ChangePrice.aspx?MODE=NEW&CustomerID={0}&ProductID={1}\" class=\"setPriceLink\">  设置价格>></a></td>", customer["CustomerID"], product["ProductID"]);
                    outHTML.Append("</tr></table>");
                }
                else if (curPrice != null)
                {
                    outHTML.AppendFormat("<td class=\"dateInPriceInfo\">|<br/>{0:d}</td>", curPrice["PriceEndDate"]);
                    outHTML.Append("</tr></table>");
                    //outHTML.AppendFormat("<input name=\"SetPrice\" class=\"Button\" onclick=\"location.href='MRP_Customer_ChangePrice.aspx?MODE=NEW&CustomerID={1}&ProductID={2}'\" type=\"button\" value=\" {0} \"/>", "调整价格>>", customer["ID"], product["ProductID"]);
                    outHTML.AppendFormat("<div class=\"setPriceLink\"><a href=\"MRP_Customer_ChangePrice.aspx?MODE=NEW&CustomerID={0}&ProductID={1}\" class=\"setPriceLink\">  调整价格>></a></div>", customer["CustomerID"], product["ProductID"]);
                    outHTML.AppendFormat("<div class=\"setPriceLink\"><a href=\"MRP_Customer_ChangePrice.aspx?MODE=List&CustomerID={0}&ProductID={1}\" class=\"setPriceLink\">  查看历史价格>></a></div>", customer["CustomerID"], product["ProductID"]);
                }

                outHTML.Append("</div>");//<div class=\"productInfoInPriceInfo\">
            }
            outHTML.Append("</div>");//<div class=\"CustomerInPriceInfo\">

        }
        return outHTML.ToString();
    }

   
}
